#pragma once
#include <iostream>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <vector>
#include <cstring>
#include <ctime>
#include <sys/wait.h>
// 先描述管道
class Channel
{
public:
    Channel(int wfd, pid_t subid)
        : _wfd(wfd),
          _subid(subid)
    {
        _name = "Channel-" + std::to_string(_wfd) + '-' + std::to_string(_subid);
    }
    int Fd()
    {
        return _wfd;
    }
    pid_t Subid()
    {
        return _subid;
    }
    std::string Name()
    {
        return _name;
    }
    void Send(int code)
    {
        int n = write(_wfd, &code, sizeof(code));
        (void)n;
    }
    void Close()
    {
        close(_wfd);
    }
    void Wait()
    {
        pid_t rid = waitpid(_subid, nullptr, 0);
        (void)rid;
    }
    ~Channel() {}

private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};

class ChannelManager
{
public:
    ChannelManager() : _next(0) {}
    void InsertChannel(int wfd, pid_t subid)
    {
        Channel c(wfd, subid);
        _Channels.push_back(c);
    }
    int size()
    {
        return _Channels.size();
    }
    Channel &select()
    {
        Channel &c = _Channels[_next];
        _next++;
        _next %= _Channels.size();
        return c;
    }
    void Printchannel()
    {
        for (auto &channel : _Channels)
        {
            std::cout << channel.Name() << std::endl;
        }
    }

    void StopSubProcess()
    {
        for (auto &channel : _Channels)
        {
            channel.Close();
            std::cout << "关闭: " << channel.Name() << std::endl;
        }
    }
    void WaitSubProcess()
    {
        for (auto &channel : _Channels)
        {
            channel.Wait();
            std::cout << "回收: " << channel.Name() << std::endl;
        }
    }
    void CloseAndWait()
    {
          for (auto &channel : _Channels)
        {
             channel.Close();
            std::cout << "关闭: " << channel.Name() << std::endl;
            channel.Wait();
            std::cout << "回收: " << channel.Name() << std::endl;
        }
    }
    ~ChannelManager() {}

private:
    std::vector<Channel> _Channels; // 所有的进程管理在这里

    int _next;
};

// const total = 5;

typedef void (*task_t)();

void PrintLog()
{
    std::cout << "我是一个打印任务" << std::endl;
}
void Download()
{
    std::cout << "我是一个下载任务" << std::endl;
}
void Upload()
{
    std::cout << "我是一个上传任务" << std::endl;
}
class TaskManager
{

public:
    TaskManager()
    {
        srand(time(nullptr));
    }
    void TaskInit()
    {
        _tasks.push_back(PrintLog);
        _tasks.push_back(Download);
        _tasks.push_back(Upload);
    }
    void Dug()
    {
        for (auto &task : _tasks)
        {
            task();
            printf("\n");
        }
    }

    void Execute(int code)
    {
        if (code >= 0 && code < _tasks.size())
        {
            _tasks[code]();
        }
    }
    int Code()
    {
        return rand() % _tasks.size();
    }
    ~TaskManager() {}

private:
    std::vector<task_t> _tasks;
};
class ProcessPool
{
public:
    ProcessPool(int num) : _process_num(num) {}
    void Work(int rfd)
    {
        while (1)
        {
            int code = 0;
            int n = read(rfd, &code, sizeof(code));//read是阻塞的，看明白了
            if (n == 0)
            {
                std::cout << "子进程退出了:" << rfd << std::endl;
                break;
            }
            else if (n < 0)
            {
                std::cout << "运行错误" << std::endl;
                break;
            }
            else
            {
                if (n != sizeof(code))
                    continue;
                else
                {
                    std::cout << "子进程接[" << getpid() << "]收到了一个任务码" << std::endl;
                    // 运行这个任务码了
                }
            }
        }
    }
    bool Create()
    {
        // 先看看如何创建一个管道
        for (int i = 0; i < _process_num; i++)
        {
            int pipefd[2] = {0};
            int n = pipe(pipefd);
            if (n < 0)
            {
                perror("pipe fail");
                return false;
            }
            // 有管道文件了，那创建子进程吧
            pid_t subid = fork();
            if (subid < 0)
            {
                return false;
            } // f->w,c->r
            else if (subid == 0)
            {
                sleep(5);
                // 进入子进程
                //其实每个子进程的读段都是3了
                std::cout<<"子："<<"pipefd[1]="<<pipefd[1]<<std::endl;
                close(pipefd[1]);
               // sleep(2);
                 std::cout<<"子："<<"pipefd[0]="<<pipefd[0]<<std::endl;
                Work(pipefd[0]);
                close(pipefd[0]);
                exit(0); // 让子进程结束，不需要子进程运行后面的的代码
            }
            else
            {
                // 父进程
                close(pipefd[0]);
                // 父进程存放信息
             //   std::cout<<"父："<<"pipefd[1]="<<pipefd[1]<<std::endl;
                _cm.InsertChannel(pipefd[1], subid);
                // close(pipefd[1]);
            }
        }
        return true;
    }
    void Debug()
    {
        _cm.Printchannel();
    }

    void Run()
    {
        // 选择一个任务码
        int taskcode = _tm.Code();
        std::cout << "选择code=" << taskcode << "作为任务码" << std::endl;
        // 选择一个信道
        auto &c = _cm.select();
        std::cout << "选择了一个子进程：" << c.Name() << std::endl;
        // 发送任务
        c.Send(taskcode);
        std::cout << "选择了一个任务码：" << taskcode << std::endl;
    }
    void Insert()
    {
        _tm.TaskInit();
    }
    int si()
    {
        return _cm.size();
    }
    void Stop()
    {
       // 关闭父进程所有的wfd即可
        _cm.StopSubProcess();
        // 回收所有子进程
        _cm.WaitSubProcess();
       // _cm.CloseAndWait();
    }

    ~ProcessPool() {}

private:
    ChannelManager _cm;
    int _process_num;
    TaskManager _tm;
};